package com.qianchang.microfinance.view.hsrecharge;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.HSReChargeDataBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 版 权: 广西鸿胜科技有限公司
 * 描 述: 金币充值
 * 修 改 人: chen G L
 * 修改时间: 2018/1/9 16:33
 */

public class HSGoldReChargeActivity extends BaseActivity{

    @BindView(R.id.webView_id)
    WebView webView;
    @BindView(R.id.progressBarLoading)
    ProgressBar mLoadingProgress;
    private String url = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hsgoldrecharge_layout);
        ButterKnife.bind(this);
        initView();

        rechargeGold();
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleName("授权");


    }

    private String pars = "";
    private String getParameter(HSReChargeDataBean bindDataBean) throws JSONException, UnsupportedEncodingException {

        Map<String,String> map = new HashMap<String,String>();
        url = bindDataBean.getAction();
        String sign = bindDataBean.getSign();
        String platformNo = bindDataBean.getPlatformNo();
        String userDevice = bindDataBean.getUserDevice();
        String keySerial = bindDataBean.getKeySerial();
        String reqData = bindDataBean.getReqData();
        String serviceName = bindDataBean.getServiceName();

        map.put("sign",sign);
        map.put("platformNo",platformNo);
        map.put("userDevice",userDevice);
        map.put("keySerial",keySerial);
        map.put("reqData",reqData);
        map.put("serviceName",serviceName);
        String parameter = "";
        String subParameter = "";

        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            parameter = parameter + key + "=" + URLEncoder.encode(value,"utf-8") + "&";
        }
        subParameter = parameter.substring(0, parameter.length() - 1);
        return subParameter;
    }

    private void rechargeGold(){
        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();
        HttpParams params = new HttpParams();
        params.put("userId", usid);
        params.put("rechargeType","coin");         //充值类型（coin：金币，money：余额）
        params.put("amount","100");                 //充值金币数量

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.RECHARGE_DO, params, new RequestCallBack<HSReChargeDataBean>() {

            @Override
            public void onSuccess(JsonResult<HSReChargeDataBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    HSReChargeDataBean bindDataBean = response.getObject();
                    if(bindDataBean != null){
                        try {
                            pars = getParameter(bindDataBean);
                            initWebView();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }else{
                        ToastUtil.getInstant().show(HSGoldReChargeActivity.this, response.getDescription());
                    }
                }else{
                    ToastUtil.getInstant().show(HSGoldReChargeActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(HSGoldReChargeActivity.this, msg);
                dismiss();
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });

    }




    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() throws JSONException, UnsupportedEncodingException {

        WebSettings settings = webView.getSettings();
        settings.setDefaultTextEncodingName("utf-8");       //设置网页默认编码
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadWithOverviewMode(true);
        //post请求(使用键值对形式，格式与get请求一样，key=value,多个用&连接)
//        urlParameter = "sign=" + URLEncoder.encode(sign,"utf-8") + "&" + "platformNo=" + URLEncoder.encode(platformNo,"utf-8") + "&" + "userDevice=" + URLEncoder.encode(userDevice,"utf-8") + "&" + "keySerial=" + URLEncoder.encode(keySerial,"utf-8") + "&" + "reqData=" + URLEncoder.encode(reqData,"utf-8") + "&" + "serviceName=" + URLEncoder.encode(serviceName,"utf-8");

        webView.setWebViewClient(new MyWebViewClient());
//        webView.setWebChromeClient(WebChromeClientProgress());       // 设置浏览器可弹窗
        settings.setJavaScriptEnabled(true);                //支持javaScript
        settings.setDomStorageEnabled(true);
        webView.postUrl(url,pars.getBytes());

    }


    // 监听
    class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边
            view.loadUrl(url);
            return true;
            //return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }

    private class WebChromeClientProgress extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (mLoadingProgress != null) {
                mLoadingProgress.setProgress(progress);
                if (progress == 100) mLoadingProgress.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, progress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    }





    //改写物理按键——返回的逻辑
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();//返回上一页面
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }



    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();
            ((WebView) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }

}
